#include<vector>
#include<stack>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
        vector<int>res;
        if (root1 == NULL && root2 == NULL) return res;
        stack<TreeNode*> stack1, stack2;
        while (root1 != NULL) {
            stack1.push(root1);
            root1=root1->left;
        }
        while (root2 != NULL) {
            stack2.push(root2);
            root2=root2->left;
        }
        while (!stack1.empty() || !stack2.empty()) {
            if (stack2.empty()||(!stack1.empty()&&stack1.top()->val <= stack2.top()->val)) {
                auto node = stack1.top();
                stack1.pop();
                res.push_back(node->val);
                node = node->right;
                while (node != NULL) {
                    stack1.push(node);
                    node = node->left;
                }
            }
            else {
                auto node = stack2.top();
                stack2.pop();
                res.push_back(node->val);
                node = node->right;
                while (node != NULL) {
                    stack2.push(node);
                    node = node->left;
                }
            }
        }
        return res;
    }
};